package com.achilles.learnviewheightwidth;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ViewTreeObserver;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextView = (TextView) findViewById(R.id.textview);

        Log.i("AchillesL", "onCreate getWidth: " + mTextView.getWidth());
        Log.i("AchillesL", "onCreate getMeasuredWidth: " + mTextView.getMeasuredWidth());
    }

    @Override
    protected void onStart() {
        super.onStart();

        Log.i("AchillesL", "onStart getWidth: " + mTextView.getWidth());
        Log.i("AchillesL", "onStart getMeasuredWidth: " + mTextView.getMeasuredWidth());

        mTextView.post(new Runnable() {
            @Override
            public void run() {
                Log.i("AchillesL", "onStart post getWidth: " + mTextView.getWidth());
                Log.i("AchillesL", "onStart post getMeasuredWidth: " + mTextView.getMeasuredWidth
                        ());
            }
        });

        ViewTreeObserver viewTreeObserver = mTextView.getViewTreeObserver();
        viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onGlobalLayout() {

                mTextView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                Log.i("AchillesL", "ViewTreeObserver getWidth: " + mTextView.getWidth());
                Log.i("AchillesL", "ViewTreeObserver getMeasuredWidth: " + mTextView
                        .getMeasuredWidth());
            }
        });
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        Log.i("AchillesL", "onWindowFocusChanged getWidth: " + mTextView.getWidth());
        Log.i("AchillesL", "onWindowFocusChanged getMeasuredWidth: " + mTextView.getMeasuredWidth());
    }
}
